package com.web3.management.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.web3.management.dto.request.ConfigRequest;
import com.web3.management.dto.request.CreateAccountConfigRequest;
import com.web3.management.dto.response.ConfigDetailResponse;
import com.web3.management.entity.Account;
import com.web3.management.entity.Config;
import com.web3.management.exception.BusinessException;
import com.web3.management.repository.AccountConfigRepository;
import com.web3.management.repository.ConfigRepository;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 配置迁移服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConfigMigrationService {

    private final ObjectMapper objectMapper;
    private final ConfigService configService;
    private final AccountService accountService;
    private final AccountConfigService accountConfigService;
    private final ConfigRepository configRepository;
    private final AccountConfigRepository accountConfigRepository;

    /**
     * 从文件导入全局配置
     */
    @Transactional
    public ConfigDetailResponse importGlobalConfigFromFile(String filePath) {
        try {
            Path path = Paths.get(filePath);
            if (!Files.exists(path)) {
                throw new BusinessException("配置文件不存在: " + filePath);
            }
            String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
            JsonNode jsonNode = objectMapper.readTree(content);

            ConfigRequest request = new ConfigRequest();
            request.setName(jsonNode.path("name").asText("导入配置"));
            request.setFilePath(filePath);
            request.setConfigContent(content);
            request.setChangeSummary("文件导入");

            return configService.createConfig(request);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("导入全局配置失败", e);
            throw new BusinessException("导入全局配置失败: " + e.getMessage());
        }
    }

    /**
     * 将现有账号迁移为独立配置
     */
    @Transactional
    public MigrationResult migrateAccountConfigs() {
        List<Account> accounts = accountService.getAllActiveAccounts();
        if (CollectionUtils.isEmpty(accounts)) {
            return new MigrationResult(0, 0, "暂无可迁移账号");
        }

        Config globalConfig = configService.getActiveConfig();
        if (globalConfig == null) {
            throw new BusinessException("请先导入并激活全局配置");
        }

        int success = 0;
        int skipped = 0;
        List<String> messages = new ArrayList<>();

        for (Account account : accounts) {
            if (accountConfigRepository.existsByAccountId(account.getId())) {
                skipped++;
                messages.add(String.format("账号 %s 已存在配置，跳过", account.getName()));
                continue;
            }
            try {
                CreateAccountConfigRequest request = buildRequestFromGlobal(globalConfig);
                request.setConfigName(account.getName() + " 默认配置");
                request.setRemark("迁移自动生成");
                accountConfigService.createAccountConfig(account.getId(), request);
                success++;
                messages.add(String.format("账号 %s 迁移成功", account.getName()));
            } catch (Exception e) {
                skipped++;
                messages.add(String.format("账号 %s 迁移失败: %s", account.getName(), e.getMessage()));
            }
        }

        return new MigrationResult(success, skipped, String.join("; ", messages));
    }

    private CreateAccountConfigRequest buildRequestFromGlobal(Config globalConfig) {
        try {
            JsonNode node = objectMapper.readTree(globalConfig.getConfigContent());
            CreateAccountConfigRequest request = new CreateAccountConfigRequest();
            request.setProjectName(node.path("name").asText());
            request.setBaseAsset(node.path("baseAsset").asText());
            request.setQuoteAsset(node.path("quoteAsset").asText("USDT"));
            request.setChainId(node.path("chainId").asInt(56));
            request.setContractAddress(node.path("contractAddress").asText());
            if (node.has("buyAmount")) {
                request.setBuyAmount(node.path("buyAmount").decimalValue());
            }
            if (node.has("targetBuyQuote")) {
                request.setTargetBuyQuote(node.path("targetBuyQuote").decimalValue());
            }
            request.setProxyEnabled(node.path("proxy").asBoolean(false));
            if (node.has("notifyUrl") && StringUtils.hasText(node.path("notifyUrl").asText())) {
                request.setNotifyUrl(node.path("notifyUrl").asText());
            }
            if (node.has("customConfig")) {
                request.setCustomConfig(node.path("customConfig").toString());
            }
            return request;
        } catch (Exception e) {
            throw new BusinessException("解析全局配置失败: " + e.getMessage());
        }
    }

    @Data
    public static class MigrationResult {
        private final int success;
        private final int skipped;
        private final String message;
    }
}
